package com.luobo.home.controller;

import com.luobo.home.pojo.JwtResponse;
import com.luobo.home.pojo.LoginRequest;
import com.luobo.home.pojo.User;
import com.luobo.home.service.UserMapper;
import com.luobo.home.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest request) {
        User user = userMapper.findByUsername(request.getUsername());
        if (user == null) {
//            throw new RuntimeException("用户不存在");
            System.out.println("用户不存在");
        }
//        System.out.println("request: " + request.getPassword());
//        System.out.println("request: " + passwordEncoder.encode(request.getPassword()));

//        System.out.println("user: " + user.getPassword());

        if (passwordEncoder.matches(request.getPassword(), user.getPassword())) {

            String token = JwtUtils.generateToken(user.getUsername());
            return ResponseEntity.ok(new JwtResponse(token));
        }
//        throw new RuntimeException("密码错误");
        System.out.println("密码错误");
        return  ResponseEntity.status(HttpStatus.BAD_GATEWAY).build();
    }


    @PostMapping("/logout")
    public ResponseEntity<?> logout() {
        // 实际逻辑已在安全配置中处理
        return ResponseEntity.ok().build();
    }
}